package org.example.struct.array2;

import java.util.Arrays;

/**
 * @author liyishan
 * @date 2024/9/18 10:04
 * @apiNote
 */

public class Test02332LatestTimeCatchTheBus {
    public static void main(String[] args) {
        int[] buses = {10,20};
        int[] passengers = {2,17,18,19};
        int capacity = 2;
        int res = latestTimeCatchTheBus(buses, passengers, capacity);
        System.out.println(res);
    }
    public static int latestTimeCatchTheBus(int[] buses, int[] passengers, int capacity) {
        Arrays.sort(buses);
        Arrays.sort(passengers);
        int pos = 0;
        int space = 0;
        for(int arrive: buses){
            space = capacity;
            while(space > 0 && pos < passengers.length && passengers[pos] <= arrive){
                space--;
                pos++;
            }
        }
        pos--;
        int lastCatchTime = space > 0 ? buses[buses.length-1] : passengers[pos];
        while(pos >= 0 && passengers[pos] == lastCatchTime){
            pos--;
            lastCatchTime--;
        }
        return lastCatchTime;
    }
}
